<template>
  <view class="page-container" :class="{ 'page-loaded': pageLoaded }">
    <!-- 顶部背景图区域 -->
    <view class="top-bg-section" :style="{ backgroundImage: `url(${currentImage})` }">
      <view class="back-btn" @click="goBack">
        <image class="back-image" src="https://zero-one01.oss-cn-shenzhen.aliyuncs.com/icon/back.png" mode="scaleToFill">
        </image>
      </view>

      <!-- 小图滑动区域 -->
      <view class="thumb-scroll">
        <scroll-view class="scroll-container" scroll-x show-scrollbar="false" :style="{ height: scrollHeight }">
          <view class="thumb-wrapper">
            <image v-for="(item, index) in currentThumbs" :key="index" :src="item.thumbUrl" class="thumb-image"
              :class="{ 'active-thumb': index === currentThumbIndex, 'thumb-clicked': index === tempClickedIndex }"
              @click="handleThumbClick(index)"></image>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 等待数据加载完成后显示内容 -->
    <view v-if="isDataLoaded">
      <!-- 选项卡 -->
      <view class="tab-bar">
        <view class="tab-item" :class="{ active: currentTab === 'forelimb' }" @click="changeTab('forelimb')">前肢</view>
        <view class="tab-item" :class="{ active: currentTab === 'flower' }" @click="changeTab('flower')">插花</view>
      </view>

      <!-- 横向滑块式选项卡 -->
      <view v-if="currentTab === 'forelimb'" class="slider-tab-bar">
        <view class="slider-tab-container">
          <view v-for="(item, index) in mingpaidata" :key="index" class="slider-tab-item"
            :class="{ 'slider-active': currentLimbTagIndex === index }" @click="handleLimbTagClick(index)">
            {{ getMingpai(index) }}
          </view>
        </view>
      </view>
      <view v-if="currentTab === 'flower'" class="slider-tab-bar">
        <view class="slider-tab-container">
          <view v-for="(item, index) in chahuaguigedata" :key="index" class="slider-tab-item"
            :class="{ 'slider-active': currentFlowerTagIndex === index }" @click="handleFlowerTagClick(index)">
            {{ getFlowerSpec(index) }}
          </view>
        </view>
      </view>

      <!-- 木料展示部分 -->
      <view class="material-section" :class="{ 'section-transition': tabChanging }">
        <text class="section-title">{{ currentSectionTitle }}</text>
        <view class="material-grid">
          <view class="material-item" v-for="(item, index) in currentMaterials" :key="index"
            @click="handleItemSelect(index)"
            :class="{ 
              'selected': (currentTab === 'forelimb' && index === selectedForelimbIndex) || 
                          (currentTab === 'flower' && selectedFlowerIndexes.includes(index)) 
            }">
            <image :src="item.pic" class="material-image"></image>
            <view class="product-info">
              <text class="price-name">{{ getQianzhi(index) }}</text>
              <text class="price-num">¥{{ item.price }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 底部信息栏 -->
      <view class="bottom-bar">
        <view class="price-info">
          <view class="price-group">
            <text class="final-price">¥{{ currentFinalPrice }}</text>
            <text class="original-price">¥{{ currentOriginalPrice }}</text>
          </view>
          <text class="delivery-tip">锁定订单后预计30个工作日交付</text>
        </view>
        <image class="action-img" :src="currentActionImage" @click="handleAction" :class="{ 'btn-clicked': btnClicked }">
        </image>
      </view>
    </view>

    <!-- 数据加载中显示的占位内容 -->
    <view v-else class="loading-placeholder">
      <text>加载中...</text>
    </view>
  </view>
</template>

<script>
import sheep from '@/sheep';

export default {
  data() {
    return {
      currentTab: 'forelimb',
      currentThumbIndex: 0,
      tempClickedIndex: 0,
      pageLoaded: false,
      tabChanging: false,
      btnClicked: false,
      // 前肢数据
      forelimbThumbs: [
        { bgUrl: 'https://zero-one01.oss-cn-shenzhen.aliyuncs.com/app/flower/f1-thumb.png', thumbUrl: 'https://zero-one01.oss-cn-shenzhen.aliyuncs.com/app/flower/f1.png' },
        { bgUrl: 'https://zero-one01.oss-cn-shenzhen.aliyuncs.com/app/flower/f1-thumb.png', thumbUrl: 'https://zero-one01.oss-cn-shenzhen.aliyuncs.com/app/flower/f1.png' },
        { bgUrl: 'https://zero-one01.oss-cn-shenzhen.aliyuncs.com/app/flower/f1-thumb.png', thumbUrl: 'https://zero-one01.oss-cn-shenzhen.aliyuncs.com/app/flower/f1.png' },
      ],
      forelimbMaterials: [],
      // 插花数据
      flowerThumbs: [
        { bgUrl: 'https://zero-one01.oss-cn-shenzhen.aliyuncs.com/app/flower/f1-thumb.png', thumbUrl: 'https://zero-one01.oss-cn-shenzhen.aliyuncs.com/app/flower/f1.png' },
        { bgUrl: 'https://zero-one01.oss-cn-shenzhen.aliyuncs.com/app/flower/f1-thumb.png', thumbUrl: 'https://zero-one01.oss-cn-shenzhen.aliyuncs.com/app/flower/f1.png' },
        { bgUrl: 'https://zero-one01.oss-cn-shenzhen.aliyuncs.com/app/flower/f1-thumb.png', thumbUrl: 'https://zero-one01.oss-cn-shenzhen.aliyuncs.com/app/flower/f1.png' },
      ],
      flowerMaterials: [],
      scrollHeight: '110rpx',
      currentImage: '',
      currentThumbs: [],
      currentMaterials: [],
      currentSectionTitle: '前肢木料',
      currentFinalPrice: '1588.00',
      currentOriginalPrice: '1588.00',
      icons: {
        forelimbArrow: 'https://zero-one01.oss-cn-shenzhen.aliyuncs.com/icon/chahua.png',
        flowerArrow: 'https://zero-one01.oss-cn-shenzhen.aliyuncs.com/icon/peizhiyulan.png'
      },
      currentActionImage: '',
      // 前肢选中索引（单选）
      selectedForelimbIndex: 0,
      // 插花选中索引（多选）
      selectedFlowerIndexes: [],
      // 横向选项卡数据
      currentLimbTagIndex: 0,
      currentFlowerTagIndex: 0,
      tabItemWidth: 80,
      mingpaidata: [],
      qianzhidata: [],
      chahuamuliaodata: [],
      chahuaguigedata: [],
      isDataLoaded: false,
    };
  },
  created() {
    // 定义所有需要等待的异步请求（返回Promise）
    const apiRequests = [
      sheep.$api.goods.detail(63), // 铭牌数据
      sheep.$api.goods.detail(64), // 前肢数据
      sheep.$api.goods.detail(65), // 插花木料数据
      sheep.$api.goods.detail(66), // 插花规格数据
    ];

    // 等待所有请求完成
    Promise.all(apiRequests)
      .then(([res63, res64, res65, res66]) => {
        // 赋值数据
        this.mingpaidata = res63.skus;
        this.forelimbMaterials = res64.skus;
        this.flowerMaterials = res65.skus;
        this.chahuaguigedata = res66.skus;

        // 数据加载完成后，初始化依赖数据的属性
        this.currentThumbs = this.forelimbThumbs;
        this.currentMaterials = this.forelimbMaterials;
        this.currentImage = this.forelimbThumbs[0].bgUrl;
        this.currentActionImage = this.icons.forelimbArrow;
        
        // 默认选中第一个插花选项
        if (this.flowerMaterials.length > 0) {
          this.selectedFlowerIndexes = [0];
        }

        // 标记数据加载完成
        this.isDataLoaded = true;
      })
      .catch((error) => {
        console.error("数据加载失败：", error);
        // 可添加错误提示（如this.$showToast('数据加载失败')）
      });
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },

    changeTab(tab) {
      if (this.currentTab === tab) return;

      this.tabChanging = true;

      setTimeout(() => {
        this.currentTab = tab;

        if (tab === 'forelimb') {
          this.currentThumbs = this.forelimbThumbs;
          this.currentMaterials = this.forelimbMaterials;
          this.currentSectionTitle = '前肢木料';
          this.currentActionImage = this.icons.forelimbArrow;
        } else {
          this.currentThumbs = this.flowerThumbs;
          this.currentMaterials = this.flowerMaterials;
          this.currentSectionTitle = '插花木料';
          this.currentActionImage = this.icons.flowerArrow;
        }

        this.currentImage = this.currentThumbs[0].bgUrl;

        setTimeout(() => {
          this.tabChanging = false;
        }, 50);
      }, 300);
    },

    getFlowerSpec(index) {
      if (this.chahuaguigedata && this.chahuaguigedata[index] && this.chahuaguigedata[index].spData) {
        try {
          const spData = JSON.parse(this.chahuaguigedata[index].spData);
          return spData['插花规格'] || '';
        } catch (error) {
          console.error('解析spData出错', error);
          return this.chahuaguigedata[index].spData || '';
        }
      }
      return '';
    },

    getMingpai(index) {
      if (this.mingpaidata && this.mingpaidata[index] && this.mingpaidata[index].spData) {
        try {
          const spData = JSON.parse(this.mingpaidata[index].spData);
          return spData['级别'] || '';
        } catch (error) {
          console.error('解析spData出错', error);
          return this.mingpaidata[index].spData || '';
        }
      }
      return '';
    },
    
    getQianzhi(index) {
      if (this.currentTab === 'forelimb') {
        if (this.forelimbMaterials && this.forelimbMaterials[index] && this.forelimbMaterials[index].spData) {
          try {
            const spData = JSON.parse(this.forelimbMaterials[index].spData);
            return spData['款式'] || '';
          } catch (error) {
            console.error('解析spData出错', error);
            return this.forelimbMaterials[index].spData || '';
          }
        }
      } else {
        if (this.flowerMaterials && this.flowerMaterials[index] && this.flowerMaterials[index].spData) {
          try {
            const spData = JSON.parse(this.flowerMaterials[index].spData);
            return spData['插花木料'] || '';
          } catch (error) {
            console.error('解析spData出错', error);
            return this.flowerMaterials[index].spData || '';
          }
        }
      }
      return '';
    },
    
    getChahua(index) {
      if (this.flowerMaterials && this.flowerMaterials[index] && this.flowerMaterials[index].spData) {
        try {
          const spData = JSON.parse(this.flowerMaterials[index].spData);
          return spData['插花木料'] || '';
        } catch (error) {
          console.error('解析spData出错', error);
          return this.flowerMaterials[index].spData || '';
        }
      }
      return '';
    },

    handleThumbClick(index) {
      this.tempClickedIndex = index;

      setTimeout(() => {
        this.currentThumbIndex = index;
        this.currentImage = this.currentThumbs[index].bgUrl;
        this.tempClickedIndex = -1;
      }, 200);
    },

    // 处理商品选择（前肢单选，插花多选）
    handleItemSelect(index) {
      if (this.currentTab === 'forelimb') {
        // 前肢保持单选
        this.selectedForelimbIndex = index;
      } else {
        // 插花改为多选
        if (this.selectedFlowerIndexes.includes(index)) {
          // 已选中，取消选择
          this.selectedFlowerIndexes = this.selectedFlowerIndexes.filter(i => i !== index);
        } else {
          // 未选中，添加选择
          this.selectedFlowerIndexes.push(index);
        }
      }
      this.handleSumPrice();
    },

    handleLimbTagClick(index) {
      this.currentLimbTagIndex = index;
      this.handleSumPrice();
    },

    handleFlowerTagClick(index) {
      this.currentFlowerTagIndex = index;
      this.handleSumPrice();
    },

    // 计算总价（修改为支持插花多选）
    handleSumPrice() {
      // 确保数据已加载完成再计算价格
      if (!this.isDataLoaded) return;
      
      // 获取选中的前肢和插花数据
      const mingpai = this.mingpaidata[this.currentLimbTagIndex] || { price: 0 };
      const qianzhi = this.forelimbMaterials[this.selectedForelimbIndex] || { price: 0 };
      const guige = this.chahuaguigedata[this.currentFlowerTagIndex] || { price: 0 };
      
      // 计算所有选中的插花材料总价
      const flowerTotal = this.selectedFlowerIndexes.reduce((sum, idx) => {
        const flower = this.flowerMaterials[idx] || { price: 0 };
        return sum + parseFloat(flower.price);
      }, 0);
      
      // 计算总价
      const totalPrice = parseFloat(mingpai.price) + parseFloat(qianzhi.price) + parseFloat(guige.price) + flowerTotal;
      
      // 更新价格显示
      this.currentOriginalPrice = totalPrice.toFixed(2);
      this.currentFinalPrice = totalPrice.toFixed(2);

      // 构建要存入storage的数据对象（包含详细信息）
      const configData = {
        mingpai: mingpai,
        qianzhi: qianzhi,
        guige: guige,
        flower: this.selectedFlowerIndexes.map(idx => this.flowerMaterials[idx]),
        currentOriginalPrice: this.currentFinalPrice,
        currentFinalPrice: this.currentFinalPrice,
        updateTime: new Date().getTime()
      };

      // 存入本地存储
      try {
        uni.setStorageSync('selectedConfig', configData);
        console.log('配置信息已存入storage:', configData);
      } catch (e) {
        console.error('存储配置信息失败:', e);
      }
    },

    handleAction() {
      if (this.currentTab === 'forelimb') {
        this.changeTab('flower');
        return;
      }

      if (!this.btnClicked) {
        uni.navigateTo({
          url: '/pages/index/canshu'
        });
        return;
      }

      this.btnClicked = true;
      setTimeout(() => {
        this.btnClicked = false;
      }, 200);
    }
  },
  mounted() {
    // 移除mounted中重复的初始化逻辑，改为在数据加载完成后统一初始化
    setTimeout(() => {
      this.pageLoaded = true;
    }, 100);
  }
};
</script>

<style scoped>
/* 页面容器 */
.page-container {
  background-color: #1a1a1a;
  color: white;
  min-height: 100vh;
  overflow-x: hidden;
  opacity: 0;
  transition: opacity 0.5s ease;
  padding-bottom: 100px;
}

.page-container.page-loaded {
  opacity: 1;
}

/* 顶部背景区域 */
.top-bg-section {
  position: relative;
  background-size: cover;
  background-position: center;
  height: 40vh;
  min-height: 300px;
  max-height: 500px;
}

.back-btn {
  position: absolute;
  top: 80rpx;
  left: 20rpx;
  z-index: 10;
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.back-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

/* 缩略图滚动区域 */
.thumb-scroll {
  position: absolute;
  bottom: 10px;
  left: 10px;
  right: 0;
  height: 110rpx;
  padding: 0 15rpx;
}

.scroll-container {
  height: 100%;
  padding-bottom: 10rpx;
}

.thumb-wrapper {
  white-space: nowrap;
  overflow-x: scroll;
  -webkit-overflow-scrolling: touch;
}

.thumb-image {
  width: 180rpx;
  height: 100rpx;
  margin-right: 20rpx;
  border: 4rpx solid transparent;
  opacity: 0.7;
  transition: all 0.3s ease;
  border-radius: 4rpx;
}

.thumb-image:active,
.thumb-image.thumb-clicked {
  transform: scale(0.95);
}

.active-thumb {
  opacity: 1;
  transform: scale(1.05);
}

/* 选项卡 */
.tab-bar {
  display: flex;
  justify-content: center;
  padding: 15px 0;
  background-color: #1a1a1a;
  position: sticky;
  top: 0;
  z-index: 10;
}

.tab-item {
  margin: 0 50px;
  padding: 10px 20px;
  font-size: 18px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  color: #999;
  /* 非激活状态灰色 */
  transition: all 0.3s ease;
}

.tab-item.active {
  color: #ffffff;
  /* 激活状态白色 */
}

.tab-item::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  width: 0;
  height: 2px;
  background-color: #ffffff;
  /* 下划线保持白色 */
  transition: all 0.3s ease;
}

.tab-item.active::after {
  left: 0;
  width: 100%;
}

/* 滑块式选项卡样式 */
.slider-tab-bar {
  background-color: #1a1a1a;
  padding: 15px 0;
  top: 60px;
  /* 基于原选项卡高度调整 */
  z-index: 9;
}

.slider-tab-container {
  display: flex;
  justify-content: center;
  align-items: center;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  padding: 0 20px;
  white-space: nowrap;
}

.slider-tab-item {
  min-width: 80px;
  font-size: 16px;
  text-align: center;
  cursor: pointer;
  color: #999;
  transition: all 0.3s ease;
  position: relative;
}

.slider-active {
  color: #ffffff;
}

/* 木料展示 */
.material-section {
  padding: 20px;
  transition: all 0.3s ease;
}

.material-section.section-transition {
  opacity: 0;
  transform: translateY(20px);
}

.section-title {
  font-size: 20px;
  margin: 15px;
  font-weight: bold;
  letter-spacing: 1px;
}

.material-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.material-item {
  border-radius: 8px;
  padding: 10px;
  transition: all 0.3s ease;
  background-color: #222;
}

.material-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}

.material-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 10px;
  transition: all 0.3s ease;
}

.material-image:hover {
  transform: scale(1.03);
}

.product-info {
  display: flex;
  color: #999;
  flex-direction: column;
  align-items: flex-start;
  gap: 5px;
}

.price-name {
  font-size: 16px;
}

.price-num {
  font-size: 14px;
}

/* 选中状态 */
.selected {
  transform: translateY(-2px);
  background-color: rgba(0, 0, 0, 0.1);
}

.selected .material-image {
  border-radius: 8rpx;
  transform: scale(1.02);
}

.selected .price-name,
.selected .price-num {
  color: #ffffff;
}

/* 底部信息栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 20;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: #0a0a0a;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.3);
}

.price-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 10px;
}

.price-group {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 15px;
}

.final-price {
  font-size: 24px;
  font-weight: bold;
  position: relative;
}

.final-price::after {
  content: '';
  right: -10px;
  top: 50%;
  width: 1px;
  height: 18px;
  background-color: #999;
  transform: translateY(-50%);
}

.original-price {
  color: #999;
  text-decoration: line-through;
  font-size: 14px;
}

.delivery-tip {
  font-size: 14px;
  color: #999;
}

.action-img {
  width: 200rpx;
  height: 80rpx;
  object-fit: contain;
  margin-left: 20rpx;
  cursor: pointer;
  transition: transform 0.2s;
}

.action-img:active,
.action-img.btn-clicked {
  transform: scale(0.95);
}

/* 加载中占位样式 */
.loading-placeholder {
  height: calc(100vh - 40vh);
  display: flex;
  justify-content: center;
  align-items: center;
  color: #999;
  font-size: 16px;
}
</style>